package com.centit.framework.ip.businessdata.controller;

import com.alibaba.fastjson.JSONArray;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.core.controller.BaseController;
import com.centit.framework.ip.businessdata.po.InterfaceManager;
import com.centit.framework.ip.businessdata.po.InterfaceMethod;
import com.centit.framework.ip.businessdata.service.InterfaceManagerManager;
import com.centit.framework.ip.businessdata.service.InterfaceMethodManager;
import com.centit.framework.ip.util.layuiResultUtil;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * InterfaceManager  Controller.
 * create by scaffold 2018-05-22
 *
 * @author guo_jh
 * T_INTERFACE_MANAGER业务系统接口配置信息表
 */


@Controller
@RequestMapping("/interface/interfacemanager")
public class InterfaceManagerController extends BaseController {
    private static final Log log = LogFactory.getLog(InterfaceManagerController.class);

    @Resource
    private InterfaceManagerManager interfaceManagerMag;
    @Resource
    private InterfaceMethodManager interfaceMethodMag;


    /**
     * 查询所有   T_INTERFACE_MANAGER  列表
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return {data:[]}
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public void list(HttpServletRequest request, HttpServletResponse response) {
        //解析参数信息
        Map<String, Object> searchColumn = convertSearchColumn(request);
        //解析分页信息
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        Integer pageNo = 1;
        Integer pageSize = 20;
        pageNo = StringUtils.isNotEmpty(page) ? Integer.valueOf(page) : pageNo;
        pageSize = StringUtils.isNotEmpty(limit) ? Integer.valueOf(limit) : pageSize;
        PageDesc pageDesc = new PageDesc(pageNo, pageSize);
        //获取业务系统信息
        JSONArray businessSystem = this.interfaceManagerMag.listObjectsAsJsonArray(searchColumn, pageDesc);
        //填充响应数据
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, businessSystem);
        resData.addResponseData(PAGE_DESC, pageDesc);
        layuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }

    /**
     * 查询单个  T_INTERFACE_MANAGER
     *
     * @param recordid RECORDID
     * @param response {@link HttpServletResponse}
     * @return {data:{}}
     */
    @RequestMapping(value = "/{handle}/{recordid}", method = {RequestMethod.GET})
    public void getInterfaceManager(@PathVariable String handle,@PathVariable String recordid,HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        InterfaceManager interfaceManager =
                interfaceManagerMag.getObjectById(recordid);
        request.setAttribute("interfaceManager",interfaceManager);
        String url = "";
        if("view".equals(handle)){
            url = "/modules/businessinterface/system-view.jsp";
        }else if("edit".equals(handle)){
            url = "/modules/businessinterface/system-edit.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增 T_INTERFACE_MANAGER，业务只有新增的时候可用此方法，如有修改可用下面 新增或保存合并的方法
     *
     * @param interfaceManager {@link InterfaceManager}
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST})
    public void createInterfaceManager(@Valid InterfaceManager interfaceManager, HttpServletRequest request, HttpServletResponse response) {
        //判断是否已存在系统标识
        InterfaceManager interfaceMag = this.interfaceManagerMag.getObjectByProperty("systemflag", interfaceManager.getSystemflag());
        if (null != interfaceMag) {
            JsonResultUtils.writeErrorMessageJson("系统标识已存在", response);
        } else {
            //填充系统信息
            interfaceManager.setRecordid(UuidOpt.getUuidAsString());
            interfaceManager.setStartOrStop("T");//默认启用
            interfaceManager.setCreater(getLoginUserCode(request));
            interfaceManager.setCreateTime(new Date());
            interfaceManagerMag.saveNewObject(interfaceManager);
            JsonResultUtils.writeSingleDataJson("操作成功", response);
        }
    }

    /**
     * 删除系统或接口
     *
     * @param recordid       主键
     * @param response
     */
    @RequestMapping(value="/{recordid}" ,method = {RequestMethod.DELETE})
    public void deleteInterfaceManager(@PathVariable String recordid, HttpServletResponse response) {
        //删除子系统下的接口
        this.interfaceMethodMag.deleteObjectByRecordId(recordid);
        //删除系统
        interfaceManagerMag.deleteObjectById(recordid);
        JsonResultUtils.writeSingleDataJson("操作成功", response);
    }

    /**
     * 删除系统或接口
     *
     * @param id       主键
     * @param datatype 接口或系统
     * @param response
     */
    @RequestMapping(method = {RequestMethod.DELETE})
    public void deleteInterfaceManager(@Valid String id, @Valid String datatype, HttpServletResponse response) {
        //根据数据类型判断系统或接口
        if ("system".equals(datatype)) {
            //删除系统下的接口
            boolean result = this.interfaceMethodMag.deleteObjectByRecordId(id);
            //删除系统
            this.interfaceManagerMag.deleteObjectById(id);
            JsonResultUtils.writeSingleDataJson("操作成功", response);
        } else if ("interface".equals(datatype)) {
            //删除接口
            this.interfaceMethodMag.deleteObjectById(id);
            JsonResultUtils.writeSingleDataJson("操作成功", response);
        } else {
            JsonResultUtils.writeErrorMessageJson("数据异常", response);
        }
    }

    /**
     * 新增或保存 T_INTERFACE_MANAGER
     *
     * @param recordid         RECORDID
     * @param interfaceManager {@link InterfaceManager}
     * @param response         {@link HttpServletResponse}
     */
    @RequestMapping(value = "/{recordid}", method = {RequestMethod.PUT})
    public void updateInterfaceManager(@PathVariable String recordid,
                                       @Valid InterfaceManager interfaceManager, HttpServletRequest request, HttpServletResponse response) {
        InterfaceManager dbInterfaceManager =
                interfaceManagerMag.getObjectById(recordid);


        if (null != dbInterfaceManager) {//如果数据库数据存在，则是更新操作
            dbInterfaceManager.copyNotNullProperty(interfaceManager);//赋值页面不为空的值，小心页面空的字符串或者改写copyNotNullProperty方法，根据自己业务需要
            //记录修改时间
            dbInterfaceManager.setUpdateTime(new Date());
            //记录修改人员
            dbInterfaceManager.setUpdater(getLoginUserCode(request));
            interfaceManagerMag.mergeObject(dbInterfaceManager);
        } else {
            interfaceManagerMag.saveNewObject(interfaceManager);//新增,注意主键赋值 UuidUtil.getTimeBasedUuid()，填写自己的业务时间，业务操作人等信息
        }

        JsonResultUtils.writeSingleDataJson("操作成功", response);
    }


    /**
     * 启用禁用功能
     *
     * @param id       主键ID
     * @param datatype 系统或接口
     * @param disabled 启用或禁用
     * @param request
     * @param response
     */
    @RequestMapping(value = "/disabled", method = {RequestMethod.PUT})
    public void disabled(@Valid String id, @Valid String datatype, @Valid String disabled, HttpServletRequest request, HttpServletResponse response) {
        //根据数据类型判断系统或接口
        if ("system".equals(datatype)) {
            //更新系统
            InterfaceManager interfaceManager = this.interfaceManagerMag.getObjectById(id);
            interfaceManager.setStartOrStop(disabled);
            interfaceManager.setUpdater(getLoginUserCode(request));
            interfaceManager.setUpdateTime(new Date());
            this.interfaceManagerMag.mergeObject(interfaceManager);
            JsonResultUtils.writeSingleDataJson("操作成功", response);
        } else if ("interface".equals(datatype)) {
            //更新接口
            InterfaceMethod interfaceMethod = this.interfaceMethodMag.getObjectById(id);
            interfaceMethod.setStartOrStop(disabled);
            interfaceMethod.setUpdateTime(new Date());
            interfaceMethod.setUpdater(getLoginUserCode(request));
            this.interfaceMethodMag.mergeObject(interfaceMethod);
            JsonResultUtils.writeSingleDataJson("操作成功", response);
        } else {
            JsonResultUtils.writeErrorMessageJson("数据异常", response);
        }
    }
}
